The differences between delete and delete[] in C++ are described in detail

  • 2020-04-01 21:25:02
  • OfStack

Have been in C++ delete and delete[] of the difference is not very understanding, met today, the Internet looked up, came to a conclusion. Make a backup so you don't lose it.
C++ tells us to use delete when retrieving the memory space of a single object allocated with new and delete[] when retrieving the memory space of a group of objects allocated with new[].
With respect to new[] and delete[], there are two cases :(1) allocate and reclaim space for basic data types; (2) allocate and reclaim space for custom types.
See the following program.
 
#include <iostream>; 
using namespace std; 
class T { 
public: 
T() { cout << "constructor" << endl; } 
~T() { cout << "destructor" << endl; } 
}; 
int main() 
{ 
const int NUM = 3; 
T* p1 = new T[NUM]; 
cout << hex << p1 << endl; 
// delete[] p1; 
delete p1; 
T* p2 = new T[NUM]; 
cout << p2 << endl; 
delete[] p2; 
} 

You can run this program yourself, and look at the different results of delete p1 and delete[] p1, and I won't post the results here.
From the result of operation, we can see that in the process of space recovery of delete p1, only the object p1[0] calls the destructor, while other objects such as p1[1] and p1[2] do not call their own destructor, which is the crux of the problem. With delete[], all objects call their destructors first before the space is reclaimed.

Objects of primitive types do not have destructors, so it should be possible to reclaim the array space composed of primitive types with delete and delete[]. But for an array of class objects, you can only use delete[]. For a single object of new, space can only be reclaimed with delete and not with delete[].

So a simple usage principle is: new and delete, new[] and delete[] are used accordingly.

Related articles: